/*
-------------------------------------------------------------------
BIE is Copyright 2001-2003 Brunswick Corp.
-------------------------------------------------------------------
Please read the legal notices (docs/legal.txt) and the license
(docs/bie_license.txt) that came with this distribution before using
this software.
-------------------------------------------------------------------
*/
package com.webdeninteractive.sbie.service;

import com.webdeninteractive.sbie.Service;
import com.webdeninteractive.sbie.Client;
import com.webdeninteractive.sbie.ProtocolHandler;
import com.webdeninteractive.sbie.ServiceEndpoint;
import com.webdeninteractive.sbie.util.DocumentUtils;
import com.webdeninteractive.sbie.util.JarPitClassLoader;
import com.webdeninteractive.sbie.exception.TransportException;
import net.iharder.Base64;

import java.util.Hashtable;
import java.util.Set;
import java.util.Iterator;
import java.util.ArrayList;
import java.io.IOException;
import java.lang.SecurityException;
import java.io.FileOutputStream;
import java.io.File;

import org.apache.log4j.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.ParserConfigurationException;

/**
 * Service implementation which downloads necessary upgrades from a
 * remote BIE instance.
 *
 * @author gfast
 * @version $Id: UpdateService.java,v 1.1.1.1 2003/05/20 16:56:49 gdf Exp $
 */
public class UpdateService
    extends ServiceBase 
    implements Service
{
    private Logger logger = Logger.getLogger("com.webdeninteractive.sbie.service.UpdateService");

    /** Utility function: tests if the classloader can load className. */
    public static boolean canLoadClass( ClassLoader cl, String className ) {
        try {
            Class c = cl.loadClass(className);
            return true;
        } catch (ClassNotFoundException x) {
            return false;
        }
    }


    /** Create and initialize a ServiceEndpoint for this Service,
     *  filling in all the request-agnostic parameters.
     *  For any call made by this service, only the method property of the EP
     *  should need to be specified further.
     */
    protected ServiceEndpoint initEndpoint() {
        ServiceEndpoint ep = protocolHandler.createServiceEndpoint( this );
        String hostname = this.getParameter("hostname");
        if (hostname==null) {
            logger.warn("Service has null hostname parameter");
        }
        String hostport = this.getParameter("hostport");
        if (hostport==null) {
            logger.warn("Service has null hostport parameter");
        }
        String soapservice = this.getParameter("SoapService");
        if (soapservice==null) {
            logger.warn("Service has null soapservice parameter");
            soapservice = "null";
        }
        if (! soapservice.startsWith("/")) {
            soapservice = "/" + soapservice;
        }
        ep.setTarget( "http://" + hostname + ":" + hostport + soapservice );
        ep.setUser( this.getParameter("username" ) );
        ep.setPassword( this.getParameter("password" ) );
        //ep.setMethod( "configRequest" ); // differs per request
        return ep;
    } 


    /** Have this service perform its task. */
    public void runService() {
        String[] classnames = config.getRequiredClassNames();
        ArrayList missingClasses = new ArrayList();
        ClassLoader cl = getParentClient().getParentSystem().getClassLoader();
        for( int i=0; i<classnames.length; i++ ) {
            logger.debug("Needed class: " + classnames[i]);
            if ( ! canLoadClass( cl, classnames[i] ) ) {
                logger.debug("Missing class: " + classnames[i]);
                missingClasses.add(classnames[i]);
            }
        }
        if ( missingClasses.size() == 0 ) { // nothing to do?
            logger.info("No file updates currently needed");
            return;
        }

        // build request out of missing classes
        // send "what do i need to get to have these classes" request
        // for each item in the response:
        //   request the jar, dl to upgradeDir, register with CL
        ServiceEndpoint ep = initEndpoint();
        try {
            logger.debug("Building request document for updateClassMapQuery");
            Document request = 
                DocumentUtils.makeDocument("updateClassMapQuery");
            Iterator mc = missingClasses.iterator();
            while(mc.hasNext()) {
                String classname = (String)mc.next();
                DocumentUtils.addTextContent( 
                    DocumentUtils.appendElement(request, "classname"),
                    classname );
            }
            request.normalize();            
            
            ep.setMethod( "updateClassMapQuery" );
            Document response = protocolHandler.sendMessage( ep, request );
            //logger.debug( DocumentUtils.dumpDoc(response) );
            Iterator reqfiles = parseMapResponse(response).iterator();
            while( reqfiles.hasNext() ) {
                String filename = (String)reqfiles.next();
                if ( downloadFile( ep, filename ) ) {
                    registerFile( filename );
                }
            }

        } catch (Exception e) {
            logger.error( "Exception building and sending request", e );
        }

    } // runService()

    protected ArrayList parseMapResponse( Document fileList ) {
        ArrayList ret = new ArrayList();
        NodeList nl = fileList.getElementsByTagName( "requiredFile" );
        for( int i=0; i<nl.getLength(); i++ ) {
            String filename = 
                DocumentUtils.getTextContent( (Element)nl.item(i) );
            if ( filename!=null && filename.length()>0 ) {
                logger.debug("Got needed filename: '" + filename + "'");
                ret.add(filename);
            } else {
                logger.debug("Big mean server gave me a null filename");
            }
        }
        return ret;
    }

    protected boolean downloadFile( ServiceEndpoint ep, String filename ) {
        try {
            logger.debug("Building request doc to dl file '" + filename + "'");
            // request that file
            Document filereq = DocumentUtils.makeDocument("updateGetFile");
            DocumentUtils.addTextContent(
                DocumentUtils.appendElement( filereq, "file" ),
                filename );
            ep.setMethod( "updateGetFile" );
            Document fileresp = protocolHandler.sendMessage( ep, filereq );
            return saveFile(filename, fileresp);
        } catch (ParserConfigurationException e) {
            logger.fatal("ParserConfigurationException shouldn't happen!", e);
            return false;
        } catch (TransportException e) {
            logger.error( "sendMessage failed", e );
            return false;
        }

    } // downloadFile()

    protected boolean saveFile( String filename, Document response ) {
        try {
            if ( response.getDocumentElement().getTagName() != "file" ) {
                logger.warn("Document element should be named 'file', I hope this is the right response...");
            }
            String hugeString = 
                DocumentUtils.getTextContent( response.getDocumentElement() );
            if (hugeString==null) {
                logger.warn("Response from getFile contained no file contents!");
                return false;
            }
            File base = config.getUpgradeStoreLocation();
            File outfile = new File(base, filename);
            if (outfile.exists()) {
                /* Always overwrite existing files: this is to recover from
                 * failed or corrupted previous download attempts.
                 * Note, however, the potential for name collisions,
                 * and the need for good name choices.
                 */
                logger.warn("Overwriting existing file!");
            }
            FileOutputStream fos = new FileOutputStream( outfile );
            Base64.OutputStream b64os = 
                new Base64.OutputStream( fos, Base64.DECODE );
            byte[] hugeBytes = hugeString.getBytes();
            b64os.write( hugeBytes, 0, hugeBytes.length );
            b64os.close();
            logger.info("Wrote " + hugeBytes.length + " bytes to " + outfile.getPath());
            return true;
        } catch (IOException e) {
            logger.warn( "Can't create or write to output file", e );
            return false;
        } catch (SecurityException e) {
            logger.warn( "Privilege problems on file write", e );
            return false;
        }
    } // saveFile()

    protected void registerFile( String filename ) {
        // register with classloader
        File base = config.getUpgradeStoreLocation();
        File location = new File( base, filename );
        try {
            JarPitClassLoader cl =
                (JarPitClassLoader)parent.getParentSystem().getClassLoader();
            cl.addJar( location );
        } catch (IOException e) {
            logger.error( "Failed to register " + location.getPath() + " with classloader!", e );
        }

    } // registerFile()
        
}


/*

get list of required classes from config
foreach reqclass:
  if ! JPCL.hasClass(reqclass):
    reqclasses.push(getclasses)
resp(jarfiles providing classes) = req(send getclasses to service)
foreach jarfile:
  resp(jarfiledata) = req(jarfilename)
  save jarfiledata to ${jarpit}/${jarfilename}
  register jarfilename with JPCL

(- if interrupted, will simply re-get jarfiles: 
    list depends on what can be loaded)

*/
